package zdream.control.world.buff;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import zdream.control.world.Box;
import zdream.control.world.MFoe;
import zdream.control.world.MFoeBuff;
import zdream.control.world.MHookType;
import zdream.control.world.MHooks;

/**
 * 掉落的道具模块, 如果 player 碰到会补血等
 * 
 * @author Zdream
 * @since 0.0.1
 * @date 2022-06-14
 */
public class MassModule extends MFoeBuff {
	public static final String CATEGORY = "mass";

	public MassModule(MFoe foe) {
		super(foe);
	}

	@Override
	public String getCategory() {
		return CATEGORY;
	}

	public void init() {
		onHook(MHookType.TICK)
				.withPriority(-30)
				.handle(this::tick)
				.buildAndSave();
	}

	public void tick() {
		handleMass();
	}

	/* **********
	 *   道具   *
	 ********** */
//	private final CheckMassEvent tmpCheckEvent = new CheckMassEvent(foe);
	/**
	 * 碰到的 Foe, 备选列表
	 */
	private final List<MFoe> candidates = new ArrayList<>();
	/**
	 * 哪个阵营的角色能发生作用
	 */
	public byte targetSide;
	public Function<MFoe, MHooks.MHookContext> massEventBuilder;

	private void handleMass() {
		MFoe player = findPlayer();
		if (player == null) {
			return;
		}

		MHooks.MHookContext context = massEventBuilder.apply(player);
		context.run();

		if (!context.aborted) {
			foe.destroy();
		}
	}

	/**
	 * MassModule 仅判断当前和模块
	 */
	private MFoe findPlayer() {
		Box box = foe.flush();
		candidates.clear();
		foe.world.findOverlapFoeAndPutInList(candidates, box.pos);
		if (candidates.isEmpty()) {
			return null;
		}

		for (MFoe foe : candidates) {
			if (foe == this.foe) {
				continue;
			}

			if (targetSide != foe.side) {
				continue;
			}

			if (MFoe.TYPE_LEADER.equals(foe.type)) {
				return foe;
			}
		}
		return null;
	}

	/* **********
	 *   工厂   *
	 ********** */

	public static class MassModuleFactory {
		MassModule module;
		public MassModuleFactory(MFoe foe) {
			module = new MassModule(foe);
		}
		public MassModuleFactory targetSide(byte targetSide) {
			module.targetSide = targetSide;
			return this;
		}
		public MassModuleFactory forHealing(Function<MFoe, MHooks.MHookContext> function) {
			module.massEventBuilder = function;
			return this;
		}
		public MassModule create() {
			if (module.massEventBuilder == null) {
				throw new IllegalArgumentException("需要设置 massEventBuilder");
			}
			module.foe.addBuff(module);
			return module;
		}
	}
}
